# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2021/10/12 15:42
# @Author  : zuodengbo
# @Email   : zuodb@amoydx.com
# @File    : commons
# @Software: PyCharm
import json
import re
import sys
import pytz
import datetime


# from dateutil.tz import tzlocal


def json_format(data: dict, default=None):
    """
    数据json格式化
    :param default:
    :param data:
    :return: 
    """
    return json.loads(json.dumps(data, default=default))


def time_now(tz=None):
    """
    返回当前时间
    :param tz:
    :return:
    """
    if tz:
        return datetime.datetime.now().replace(tzinfo=pytz.timezone(tz))

    return datetime.datetime.now()


def active_time(d=0, m=1, s=0):
    """
    返回有效期时间
    :param d:
    :param m:
    :param s:
    :return:
    """

    return time_now() + datetime.timedelta(days=d, minutes=m, seconds=s)


def str_to_datetime(time_str, fmt="%Y-%m-%d"):
    """
    时间string类型转换为date类型
    :param time_str: like "2021-10-14"
    :param fmt:
    :return:
    """
    return datetime.datetime.strptime(time_str, fmt)


def time_to_str(time, fmt="%Y-%m-%d %H:%M:%S"):
    """
    时间date类型转换为string类型
    :param time:
    :param fmt:
    :return: 
    """
    return datetime.datetime.strftime(time, fmt)


def str2fun(a_str):
    """
    字符串转函数
    :param a_str: 
    :return: 
    """
    module, _, function = a_str.rpartition('.')
    if module:
        __import__(module)
        mod = sys.modules[module]
    else:
        mod = sys.modules["__main__"]  # or whatever's the "default module"
    return getattr(mod, function)


def check_phone_number(phone):
    """
    校验手机号
    :param phone:
    :return:
    """
    reg = r"^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$"
    result = re.match(reg, phone)
    if result:
        return True
    else:
        return False


def check_email(email):
    """
    校验邮箱
    :param email:
    :return:
    """
    regx = r"[\w][a-zA-Z1-9.]{4,19}@[a-zA-Z0-9]{2,3}.[com|gov|net]"
    ex_email = re.compile(regx)
    result = ex_email.match(email)
    if result:
        return True
    else:
        return False


class DateEncoder(json.JSONEncoder):
    """
    datetime格式数据JSON序列化时的处理
    """

    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, obj)


if __name__ == '__main__':
    print(str_to_datetime("2021-10-14"))
    print(time_now("UTC"))
    print(time_now("Asia/Shanghai"))
    print(time_now())
    # print(datetime.datetime.now(tzlocal()).tzname())
    print(str2fun("tasks.tasks.time_job"))
